<script lang="ts" setup>
import { ElMessage, ElTable } from 'element-plus'
import { ref } from 'vue'
import qs from 'qs'
import { GetRelationproduct, PostRelationproduct, cancelCoupon, patchListSort } from '@/api/modules/voucher.ts'
import { GetAllData } from '@/api/modules/merchandiseControl.ts'

const route = useRoute()

// 加载
const loading = ref(false)
// 商品列表对话框
const dialogTableVisible = ref(false)
const imgDomain = 'https://img1.eprhan.cc'

// 券信息和关联产品列表
const dataList = ref({
  coupon: {
    id: undefined,
    name: '',
    picUrl: '',
    price: undefined,
    type: undefined,
    productCode: '',
  }, // 券信息
  productList: [],
})

// 展示列表
const productList = ref([])
// 所有的商品信息
let productListSource: any = []

const ProductName = ref('')
// 列表选中
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref([])
function handleSelectionChange(val: any) {
  multipleSelection.value = val
}

// 获取数据
async function GetDataList() {
  loading.value = true
  const id = route.query.id as string
  await GetRelationproduct({ id }).then((res: any) => {
    if (res.succeeded) {
      dataList.value.coupon = res.data.coupon
      dataList.value.productList = res.data.productList
      // total.value = res.data.total
      loading.value = false
      // console.log(res.data)
    }
  })

  const params = qs.stringify({ ProductName: '', IsActive: true, FlagList: [1, 3, 7] })

  await GetAllData(params).then((res: any) => {
    // console.log(res.data)
    if (res.succeeded) {
      productListSource = res.data
      // 从所有的商品中筛选掉已经关联的商品
      productList.value = productListSource.filter((item: any) =>
        !dataList.value.productList.some((excludeItem: any) => excludeItem.productId === item.productId),
      )
      productListSource = productList.value
    }
  })
}

// 搜索
function Search() {
  // console.log('触发')
  productList.value = productListSource.filter((item: any) => item.productName.includes(ProductName.value) || String(item.productId).includes(ProductName.value))
}
// 新增
function AddCoupon() {
  const params = {
    id: route.query.id as string,
    productIdList: multipleSelection.value.map((item: any) => item.productId),
  }
  PostRelationproduct(params).then((res: any) => {
    // console.log(res)
    if (res.succeeded) {
      ElMessage.success('关联成功')
      dialogTableVisible.value = false
      GetDataList()
    }
    else {
      ElMessage.error(`关联失败,${res.errors}`)
    }
  })
}

// 修改排序
function SortModification(message: any) {
  const params = {
    id: route.query.id,
    productId: message.row.productId,
    sort: message.row.sort,
  }
  // console.log(params)
  patchListSort(params).then((res: any) => {
    if (res.data) {
      ElMessage.success('修改成功。')
    }
    else {
      ElMessage.error('修改失败。')
      GetDataList()
    }
  })
}

function Cancel(id: number) {
  const data = {
    id: route.query.id,
    productId: id,
  }
  cancelCoupon(data).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('取消成功')
      GetDataList()
    }
    else {
      ElMessage.error('取消失败')
    }
  })
}

// function SetIndex() {
//   console.log(dataList.value.productList)
// }

onMounted(() => {
  GetDataList()
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="from">
          <el-image
            :src="imgDomain + dataList?.coupon?.picUrl"
            style="width: 120px; margin-right: 10px;"
          />
          <el-descriptions class="margin-top" :column="2" border>
            <el-descriptions-item label="券ID">
              {{ dataList.coupon.id }}
            </el-descriptions-item>
            <el-descriptions-item label="券名称">
              {{ dataList.coupon.name }}
            </el-descriptions-item>
            <el-descriptions-item label="券面值">
              {{ dataList.coupon.price }}
            </el-descriptions-item>
            <el-descriptions-item label="券类型">
              {{ dataList.coupon.type === 1 ? '赠品券' : '' }}
            </el-descriptions-item>
            <el-descriptions-item label="商品编码">
              {{ dataList.coupon.productCode }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <ElDivider border-style="dashed" />
        <div class="text-right">
          <el-button @click="dialogTableVisible = true">
            关联商品
          </el-button>
          <!-- <el-button type="primary" @click="SetIndex">
            调整顺序
          </el-button> -->
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <ElTable v-loading="loading" :data="dataList.productList" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="productId" label="商品ID" width="100" />
        <el-table-column header-align="center" prop="productName" label="商品名称" />
        <el-table-column align="center" prop="salePrice" label="商品价格" width="120" />
        <el-table-column align="center" prop="sort" label="排序" fixed="right" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.sort" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="SortModification(scope)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-popconfirm title="你确定要取消关联吗?" @confirm="Cancel(scope.row.productId)">
              <template #reference>
                <el-button type="danger">
                  取消关联
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </ElTable>
    </PageMain>
    <el-dialog v-model="dialogTableVisible" title="选择商品" width="1000">
      <el-form>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="商品ID或名称">
              <el-input v-model="ProductName" @input="Search" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="AddCoupon">
              关联商品
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <ElTable ref="multipleTableRef" :data="productList" border height="600" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column align="center" property="productId" label="商品ID" width="100" />
        <el-table-column property="productName" label="商品名称" />
        <el-table-column align="center" prop="salePrice" label="商品价格" width="120" />
      </ElTable>
    </el-dialog>
  </div>
</template>

<style scoped>
.from {
  display: grid;
  grid-template-columns: 1fr 6fr;
  padding: 20px 25px 0;
}
</style>
